<?php

namespace app\common\controller;

use app\admin\model\HomeUser;
use app\api\controller\Auth;
use app\BaseController;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\exception\HttpResponseException;

class ApiController extends BaseController
{

    protected $noTokenVerifyAction  = [];

    protected $modelUser = null;

    public function initialize()
    {
        parent::initialize();


        if (!in_array($this->request->action(), $this->noTokenVerifyAction)) {
            $this->verifyToken();
        }
    }

    public function verifyToken()
    {

        $token = $this->request->header('session_token');

        if (!empty($token)) {


            $api_key = sysconfig('site', 'api_key');

            try {
                $auth_info = JWT::decode($token, new Key($api_key, Auth::AUTH_ALGORITHM));
            } catch (\Throwable $th) {

                return $this->returnMessage('登录认证失败:' . $th->getMessage(), 700);
            }

            $expire_time = $auth_info->expire_time;

            if ($expire_time < time()) {
                return $this->returnMessage('登录认证已过期', 700);
            }


            $model_user = HomeUser::where('username', $auth_info->username)->find();

            if (empty($model_user)) {
                return $this->returnMessage('登陆失败，用户不存在', 700);
            }

            $this->modelUser = $model_user;
        }
    }

    public function initPath($path)
    {

        $path = $this->modelUser->home_path  . $path;

        return substr($path, 0, -1);
    }

    public function requestData($validate = null)
    {

        $post_data = $this->request->post();

        if (!empty($validate)) {
            if (!$validate->check($post_data)) {
                return $this->returnMessage($validate->getError());
            }
        }

        return $post_data;
    }

    public function returnMessage($data = [], $code = 0, $msg = '')
    {


        throw new HttpResponseException(
            json_message($data, $code, $msg)
                ->header([
                    'Access-Control-Allow-Origin' => '*',
                    'Access-Control-Allow-Credentials' => 'true',
                    'Access-Control-Max-Age'           => 1800,
                    'Access-Control-Allow-Methods'     => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
                    'Access-Control-Allow-Headers'     => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With, SESSION-TOKEN',
                ])
        );
    }
}
